import config from '@/config/config.js'

// 请求拦截器
const httpInterceptor = {
  invoke(options) {
    // ... 其他请求拦截逻辑 ...
  },
  
  success(res) {
    // 处理 400 状态码
    return res
  },
  
  fail(err) {
    // ... 错误处理逻辑 ...
  }
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

// 请求封装
const request = {
  post(url, data, options = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: config.util.getApiUrl(url),
        data,
        method: 'POST',
        header: {
          ...config.request.headers,
          ...config.request.getCommonHeaders(),
          ...options.headers
        },
        timeout: options.timeout || config.request.timeout,
        success: (res) => {
          if (res.data.code === 401) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            })
          }
          resolve(res)
        },
        fail: reject
      })
    })
  },
  
  upload(url, filePath, options = {}) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: config.util.getApiUrl(url),
        filePath,
        name: options.name || 'file',
        header: {
          ...config.request.getCommonHeaders(),
          ...options.headers
        },
        success: resolve,
        fail: reject
      })
    })
  },
  
  get(url, params = {}, options = {}) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: config.util.getApiUrl(url),
        data: params,
        method: 'GET',
        header: {
          ...config.request.headers,
          ...config.request.getCommonHeaders(),
          ...options.headers
        },
        timeout: options.timeout || config.request.timeout,
        success: resolve,
        fail: reject
      })
    })
  }
}

// 导出 request 和 config
export { request as default, config } 